<template>
  <div class="container">
    <!-- 表单 -->
    <el-form ref="addForm" :model="form" :rules="rules">
      <el-form-item
        label="活动名称"
        :label-width="formLabelWidth"
        prop="subjectName"
      >
        <!-- prop="subjectName" -->
        <el-input
          v-model="form.subjectName"
          placeholder="请输入学科名称"
          autocomplete="off"
        />
      </el-form-item>
      <el-form-item label="是否显示" :label-width="formLabelWidth">
        <el-switch
          v-model="form.isFrontDisplay"
          active-color="#13ce66"
          inactive-color="#ff4949"
        />
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="hCancel">取 消</el-button>
      <el-button type="primary" @click="hSubmit">确 定</el-button>
    </div>
  </div>
</template>

<script>
import { add, update, detail } from '@/api/hmmm/subjects'

export default {
  props: {
    curId: {
      type: Number,
      default: null
    },
    isEdit: {
      type: Boolean,
      required: true
    }
  },
  data() {
    return {
      form: {
        subjectName: '', // 学科名称
        isFrontDisplay: true // 前台是否显示
      },
      formLabelWidth: '80px',
      rules: {
        subjectName: [
          { required: true, message: '请输入学科名称', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    !this.isEdit || this.backfill()
  },
  methods: {
    // 新增学科
    async doAdd() {
      try {
        const res = await add(this.form)
        console.log('add', res)
        this.$message.success('添加成功')
        // 通知父组件
        this.$emit('success')
        // 清空表单
        this.form = {
          subjectName: '', // 学科名称
          isFrontDisplay: '' // 前台是否显示
        }
      } catch (err) {
        this.$message.error('添加失败')
        console.log('add', err)
      }
    },
    // 数据回填
    async backfill() {
      try {
        const res = await detail({ id: this.curId })
        console.log(res)
        res.data.isFrontDisplay === 1 ? res.data.isFrontDisplay = true : res.data.isFrontDisplay = false
        this.form = res.data
      } catch (err) {
        this.$message.error('获取失败')
      }
    },
    // 修改学科
    async doEdit() {
      try {
        const res = await update(this.form)
        console.log(res)
        this.$emit('close')
        this.$message.success('修改成功')
      } catch (err) {
        this.$message.error('修改失败')
        console.log(err)
      }
    },
    hCancel() {
      this.$emit('close')
    },
    hSubmit() {
      // 手动兜底校验
      this.$refs.addForm.validate((valid) => {
        if (valid) {
          this.isEdit ? this.doEdit() : this.doAdd()
        }
      })
    }
  }
}
</script>

<style scoped lang="scss">
.dialog-footer {
  text-align: right;
}
</style>
